<?php

require_once 'classes/LightPressPlugin.php';

class Stats extends LightPressPlugin {
    
    var $constructor_args = array(
        'replace_index'=>'remove this page from URL',
        'server_side_logging'=>'log traffic from inside the Frontend without using Javascript/img on the client',
        'ua_skip'=>'list of user agents (or user agents tokens) to skip (one per line)');
    
    var $replace_index = 'index.php';
    var $server_side_logging = false;
    var $ua_skip = "Googlebot\nMSIECrawler\nMozilla/4.0 (compatible; MSIE 4.0; Windows NT; ....../1.0 )\nMozilla/4.5 (compatible; HTTrack 3.0x; Windows 98)";
    
    var $default_context = LP_CONTEXT_ALL;
    var $description = 'Log traffic to a db table';
    
    var $active = true;
    var $hooks = array('pre_render');
    
    var $_table = "(
        id bigint(20) NOT NULL auto_increment,
        log_id varchar(32) NOT NULL default '',
        host varchar(15) NOT NULL default '',
        url varchar(192) NOT NULL default '',
        query_string varchar(255) NOT NULL default '',
        referrer varchar(255) NOT NULL default '',
        referrer_query_string varchar(255) NOT NULL default '',
        user_agent varchar(128) default NULL,
        day date NOT NULL default '0000-00-00',
        time time default NULL,
        usertrack varchar(48) default NULL,
        context varchar(24) default NULL,
        postname varchar(200) default '',
        feed tinyint(1) default '0',
        PRIMARY KEY  (id),
        KEY log (log_id),
        KEY referrer (referrer),
        KEY url (url),
        KEY day (day),
        KEY idx_usertrack (usertrack),
        KEY stats_context (context),
        KEY stats_postname (postname),
        KEY stats_feed (feed)
    )";

    var $_col_postname = " ADD COLUMN postname varchar(200) default '' AFTER context";
    var $_key_postname = " ADD INDEX stats_postname (postname)";
    
    function Stats(&$frontend, $args, $dummy_run=false) {
        $this->LightPressPlugin($frontend, $args, $dummy_run);
        
        if ($this->server_side_logging) {
            $this->hooks = array('shutdown'); // use a different hook to catch feeds?
            $frontend->tpl->setVar('PLUGIN_STATS', '');
        }
        
        $this->ua_skip_array = explode("\n", $this->ua_skip);
    }
    
    function run($hook, &$hook_data) {
        
        $ua =& $_SERVER['HTTP_USER_AGENT'];
        
        foreach ($this->ua_skip_array as $agent) {
            if (stristr($ua, $agent) !== false)
                return $this->hide();
        }
        
        switch ($hook) {
            case 'pre_render':
                return $this->clientSideLogging();
                break;
            case 'shutdown':
                return $this->serverSideLogging();
                break;
        }
    }
    
    function clientSideLogging() {
        $o =& $this->_frontend->options;

        $referer = isset($_SERVER['HTTP_REFERER']) ? urlencode($_SERVER['HTTP_REFERER']) : '';
        $uri = isset($_SERVER['REQUEST_URI']) ? urlencode($_SERVER['REQUEST_URI']) : '/';
        if (is_string($rp = $this->replace_index) && substr($uri, -strlen($rp)) == $rp) {
            $uri = substr($uri, 0, (strlen($uri) - strlen($rp)));
        }
        $context =& $this->_frontend->context['type'];
        $postname = (($context == 'post') || ($context == 'static')) ? $this->_frontend->context['filter'] : '';
        $this->_frontend->tpl->setVar(
            'PLUGIN_STATS',
            "<script type=\"text/javascript\" language=\"JavaScript1.2\">//<![CDATA[
            var stat_img_url = '{option_url}/stats.gif?l={$o['shortname']}&amp;' +
            'r=' + escape(document.referrer) + '&amp;' +
            'u=$uri&amp;' +
            'c=$context&amp;' +
            'p=$postname';
            document.write('<img src=\"' + stat_img_url + '\" width=\"1\" height=\"1\" alt=\"\" border=\"0\" />');
        //]]></script>");
    }
    
    function serverSideLogging() {

        $o =& $this->_frontend->options;
        
        $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
        if (is_string($rp = $this->replace_index) && substr($uri, -strlen($rp)) == $rp) {
            $uri = substr($uri, 0, (strlen($uri) - strlen($rp)));
        }
        
        $usertrack = '';
        foreach ($_COOKIE as $k => $v) {
            if (strstr($k, 'wordpressuser_'))
                return;
            else if ($k == 'Apache')
                $usertrack = $v;    // TODO: set a unique cookie
        }

        $uri = explode('?', $uri, 2);
        if (count($uri) == 1)
            $uri[] = '';
        
        $referrer = explode('?', $referrer, 2);
        if (count($referrer) == 1)
            $referrer[] = '';
        
        $context =& $this->_frontend->context['type'];
        $postname = (($context == 'post') || ($context == 'static')) ? $this->_frontend->context['filter'] : '';
        
        $q = "INSERT INTO {$this->_frontend->tables['stats']} VALUES (NULL,
                '{$o['shortname']}', '{$_SERVER['REMOTE_ADDR']}', '{$uri[0]}',
                '{$uri[1]}', '{$referrer[0]}', '{$referrer[1]}',
                '{$_SERVER['HTTP_USER_AGENT']}', 
                '" . gmstrftime("%Y-%m-%d") . "', '" . gmstrftime("%H:%M:%S") . "',
                '$usertrack', '$context', '$postname', 0)";
        $this->_frontend->db->query($q);
    }
        
    function install() {
        // grab the table prefix and db
        global $table_prefix, $wpdb;

        $table = "${table_prefix}stats";
        $found = false;
        foreach ($wpdb->get_results("show tables;", ARRAY_N) as $row) {
            if ($row[0] == $table) {
                $found = true;
                break;
            }
        }
        
        if (!$found) {
            $res = $wpdb->get_results("create table $table " . $this->_table);
        } else {
            // add missing columns
            $found_postname = false;
            foreach ($wpdb->get_results("SHOW COLUMNS IN $table;", ARRAY_N) as $row) {
                if ($row[0] == 'postname') {
                    $found_postname = true;
                    break;
                }
            }
            if (!$found_postname) {
                $res = $wpdb->get_results("ALTER TABLE $table " . $this->_col_postname);
                $res = $wpdb->get_results("ALTER TABLE $table " . $this->_key_postname);
            }
        }
        // check result?
        
    }
    
}

?>
